<?php
namespace Home\Controller;

use MyBase\Tool;
use MyBase\BaseController;


class UserController extends BaseController{

	public function userLogin(){
		//获取整个post
		$postData = I("post.");
		// print_r($postData);exit;
		//首先验证 验证码
		$verify = new \Think\Verify(); 
		if(!isset($postData['no_verify'])){
			if(!$verify->check($postData['user_verify'])){
				//验证不通过
				$this->ajaxReturn(false,'Verify error！');
			}			
		}
 		//判断email还是用户名
		$isEmailRes = Tool::isEmail($postData['username']);
		
		if($isEmailRes){
			$res = $this->UserModel->getUserInfoByUserEmail($postData['username']);
		}else{
			$res = $this->UserModel->getUserInfoByUserName($postData['username']);
		}
		if(!$res){
			$this->ajaxReturn(false,'User not exsit!');
		}
		if(!cookie("USER")){
			if(md5(md5($postData['userpwd']).$res['salt']) != $res['password']){
				$this->ajaxReturn(false,'Password error');
			}
		}
		session('login_user',$res); 	
		if($postData['remember'] == 'on'){
			cookie('USER',$res,604800);
		}

		$this->ajaxReturn(true,'登录成功');
	}

	/**
	 * 检查用户是否登录
	 */
	public function checkUserLogin(){
		$login = session('login_user');
		if(!$login){
			$this->ajaxReturn(false,'error--no login');
		}
		$this->ajaxReturn(true,'logined');
	}
	/**
	 * [userLoginOut 用户退出]
	 * @return [type] [description]
	 */
	public function userLoginOut(){
		session('login_user',null);
		$this->ajaxReturn(true,'您已成功退出');
	}

	/**
	 * ajax检查验证码输入是否正确
	 */
	public function ajaxCheckVerify(){
		$postData = I("post.");
		$verify = new \Think\Verify(); 
		if(!$verify->check($postData['vcode'])){
			//验证不通过
			$this->ajaxReturn(false,'Verify error！');
		}
		$this->ajaxReturn(true,'Verify sucess!');
	}

	/**
	 *用户注册 
	 */
	public function register(){
		$this->assign('myCarNum', $this->carNum);
		$this->display('index/register');
	}

	/**
	 * 检测用户名是否唯一
	 */
	public function ajaxCheckNameUnique(){
		$userName = I('post.name');
		$res = $this->UserModel->checkUserNameUnique($userName);
		if(!$res){
			$this->ajaxReturn(true,'用户可以注册');
		}
		$this->ajaxReturn(false,'用户名已被注册');
	}

	/**
	 * 检测邮箱是否唯一
	 */
	public function ajaxCheckEmailUnique(){
		$userEmail = I('post.email');
		$res = $this->UserModel->checkEmailUnique($userEmail);
		if(!$res){
			$this->ajaxReturn(false,'邮箱已被注册');
		}
		$this->ajaxReturn(true,'邮箱可以使用');
	}	

	/**
	 * 用户名注册   数据库自动验证
	 */
	public function ajaxRegisterByName(){
		$postData = I('post.');
		if($postData['register_protocol'] != 'on'){
			$this->ajaxReturn(false,'请同意来吃网协议');
		}
		if($postData['register_password'] != $postData['register_repassword']){
			$this->ajaxReturn(false,'两次密码输入不一致');
		}
		$salt = $this->produceSalt();
		//拼数据
		$data['name'] = $postData['register_name'];
		$data['password'] = md5(md5($postData['register_password']).$salt);
		$data['salt'] = $salt;
		if(!$this->UserModel->create($data)){
			$this->ajaxReturn(false,$this->UserModel->getError());
		}
		$res = $this->UserModel->filter('strip_tags')->add();
		if(!$res){
			$this->ajaxReturn(false,'注册失败');
		}
		$this->ajaxReturn(true,'注册成功');
	}
	/**
	 * 邮箱注册   后台自个验证
	 */
	public function ajaxRegisterByEmail(){
		$postData = I('post.');
		if($postData['register_protocol_'] != 'on'){
			$this->ajaxReturn(false,'请同意来吃网协议');
		}
		if($postData['register_password_'] != $postData['register_repassword_']){
			$this->ajaxReturn(false,'两次密码输入不一致');
		}
		$isEmailRes = Tool::isEmail($postData['register_email']);
		if(!$isEmailRes){
			$this->ajaxReturn(false,'邮箱格式不正确');
		}
		$salt = $this->produceSalt();
		$data['name'] =  $postData['register_email'];
		$data['email'] = $postData['register_email'];
		$data['password'] = md5(md5($postData['register_password_']).$salt);
		$data['salt'] = $salt;
		$res = $this->UserModel->data($data)->add();
		if(!$res){
			$this->ajaxReturn(false,'注册失败了');
		}
		$this->ajaxReturn(true,'恭喜您注册成功');
	}
	/**
	 * 生成盐
	 * 
	 */
	private function produceSalt(){
		return mt_rand(1000,99999);
	}

	/**
	 * 密码找回(1)    这个是密码找回填写邮箱的页面，填写完邮箱后点击找回密码会触发afterClickPwdFind
	 * 主要涉及的四个方法如下：
	 * userPwdfind();
	 * afterClickPwdFind();
	 * userPwdFindChk();
	 * userPwdFindChkChk();
	 */
	public function userPwdFind(){
		$this->assign('position',array(__MODULE__=>'首页',__ACTION__=>'密码找回'));
		$this->display("Index/userpwdfind");
	}

	/**
	 * 点击找回密码后,发送邮件(2)   
	 * 1.获取邮箱
	 * 2.成code，生成过期时间，存入数据库（这步是为了防止链接始终有效的情况）
	 * 3.发送邮件
	 */
	public function afterClickPwdFind(){
		$postData = I("post.");
		$userInfo = $this->UserModel->getUserInfoByUserEmail($postData['email']);
		if(!$userInfo){
			$this->ajaxReturn(false,'邮箱无效！请检查！');
		}
		$mail = new \Org\Net\PHPMailer();
		//发送方设置
		$mail->IsSMTP();//使用SMTP方式发送
		$mail->IsHtml();
		$mail->SMTPAuth 	=	true;//启用SMTP验证功能
		$mail->Host 		=	"smtp.163.com";//SMTP服务器【这里的参数设置可以参考我的另一篇博文：如何得到发送邮件服务器地址（SMTP地址）？】
		$mail->Port 		=	C("system_smtp_port");//SMTP服务器的端口号
		$mail->CharSet 		=	'UTF-8';
		$mail->Username 	=	C("system_email_username");//你的QQ号(格式374452668或者374452668@qq.com)
		$mail->Password 	=	C("system_email_password");//你的邮箱密码
		$mail->From 		=	C("system_email_address");//邮件发送者email地址(请填写完整的email地址)
		$mail->FromName 	=	C("system_email_called");//你的email昵称

		//生成code，生成过期时间，存入数据库
		$data['pwdfind_code'] 		= uniqid('',true);
		$data['pwdfind_timeout'] 	= time()+C('pwdfind_timeout_minutes')*60;
		$data['pwdfind_uid'] 		= $userInfo['id'];
		
		//接收方设置
		$toemail = $postData['email'];
		$pos = strpos($toemail, "@");
		$toname = substr($toemail, 0,$pos);
		$mail->AddAddress($toemail,$toname);//收件人的email地址和昵称,格式AddAddress("收件人email","收件人姓名")
		$a = U('User/userPwdFindChk',array('uid'=>$data['pwdfind_uid'],'code'=>$data['pwdfind_code']));
		$mail->Body="<h1>我是Commingle Eatting 管理员  你好</h1>点击以下链接重置密码<br/><a href='http://localhost:8080$a'>"."http://localhost:8080".$a."</a><br>此链接".C('pwdfind_timeout_minutes')."分钟后过期";//邮件内容
		$mail->Subject="密码找回邮件";//邮件标题
		if($mail->Send()){
			$this->PwdfindModel->data($data)->add();
			$this->ajaxReturn(true,'邮件已发送，请查收！');
		}else{
			$this->ajaxReturn(false,'邮件发送失败，请检查网络是否通畅!');
		}
	}
	/**
	 * 重置密码(3) 这步进去输入新密码的页面
	 * 1.检测加密字符串（code）是否与之前生成的一致(防止用户修改了url的字符串)
	 * 2.检测过期时间
	 * 3.显示页面
	 */
	public function userPwdFindChk(){
		$getData = I("get.");
		$res = $this->PwdfindModel->getInfoByUid($getData['uid']);
		$tF = 1;
		if($getData['code'] != $res['pwdfind_code']){
			$tF = 0;
		}
		// echo $res['pwdfind_timeout'].'-',time();
		if($res['pwdfind_timeout'] < time()){
			$tF = 0;
		}
		$this->assign('tF',$tF);
		$this->assign('user_id',$getData['uid']);
		$this->assign('position',array(__MODULE__=>'首页',__ACTION__=>'密码重置'));
		$this->display("Index/userpwdfindchk");
	}

	/**
	 * 重置密码处理(4)  这个是填写完密码后点击确认后的处理程序，主要是修改用户密码
	 * 1.根据用户Id获取用的信息
	 * 2.将新的密码和用户的盐一起加密
	 * 3.更新数据库
	 */
	public function userPwdFindChkChk(){
		$postData = I("post.");
		$res = $this->UserModel->getUserInfoById($postData['id']);
		$res['password'] = md5(md5($postData['password']).$res['salt']);
		$saveRes = $this->UserModel->save($res);
		if($saveRes === false){
			$this->PwdfindModel->where("pwdfind_uid={$postData['id']}")->delete();
			$this->ajaxReturn(false,'密码重置失败');
		}else{
			$this->PwdfindModel->where("pwdfind_uid={$postData['id']}")->delete();
			$this->ajaxReturn(true,'密码重置成功');
		}
	}
}